package org.thewares.collection.test;

object Timer {
      case class Timing(val millis:Double, val kb:Double){
	    override def toString= millis+"ms, "+kb+"kb.";
      }
      case class TimedValue[T](val timing:Timing,val t:T);

      def time[T <: AnyRef](count:Int,f: =>T):TimedValue[T] = {
	    Runtime.getRuntime.gc()
	    var totalT=0L;
	    var totalM=0L;
	    var ret:T=null.asInstanceOf[T];
	    for (i <- 1 to count) {
		  ret=null.asInstanceOf[T];
		  Runtime.getRuntime.gc()
		  val startM =Runtime.getRuntime.freeMemory
		  val startT =System.nanoTime;
		  ret=f;
		  val deltaT=System.nanoTime-startT;
		  val deltaM=startM-Runtime.getRuntime.freeMemory;
		  
		  if(deltaT>0){totalT += deltaT;}
		  if(deltaM>0){totalM += deltaM;}else {
			println("hmm, deltaM="+deltaM);
		  }

	    }
	    TimedValue(Timing((totalT/1000)/(1000.0d * count),totalM/(1000.0d * count)),ret);
      }



}
